#include "IndiceTerminos.h"

IndiceTerminos::IndiceTerminos(const char* filename):Archivo(filename) {
	v.clear();
	load();
}

void IndiceTerminos::add(string termino, uint32_t offset) {
	RegistroT r;
	r.termino = new char[termino.length() + 1];
	strcpy(r.termino, termino.c_str());
	r.offset = offset;

	unsigned short int numBytes;
	numBytes = termino.length() + sizeof(uint32_t);

	this->clear();

	this->write((char*) &numBytes, sizeof(unsigned short int));
	this->write((char*) &r, numBytes);
}

void IndiceTerminos::load() {
	while (!this->eof()) {
		RegistroT* r = new RegistroT;
		unsigned short int numBytes;

		this->read((char*) &numBytes, sizeof(unsigned short int));
		this->read((char*) r, numBytes);

		this->v.push_back(r);
	}
}

uint32_t IndiceTerminos::getStartOffset(string termino) {
	for (unsigned int i = 0; i < v.size(); i++) {
		RegistroT* r = v.at(i);
		if (string(r->termino) > termino) {
			if (i == 0)
				return 0;
			return v.at(i - 1)->offset;
		}

		else if (string(r->termino).compare(termino) == 0) {
			return v.at(i)->offset;
		}
	}

	return v.at(v.size())->offset;
}

uint32_t IndiceTerminos::getFinalOffset(string termino) {
	for (unsigned int i = 0; i < v.size(); i++) {
		RegistroT* r = v.at(i);
		if (string(r->termino) > termino) {
			if (i == 0)
				return 0;
			return r->offset;
		}

		else if (string(r->termino).compare(termino) == 0) {
			return v.at(i)->offset;
		}
	}

	return 0;
}

IndiceTerminos::~IndiceTerminos() {
	for (unsigned int j = 0; j < v.size(); j++) {
		RegistroT* r = v.at(j);
		if (r != NULL)
			delete r;
	}

	v.clear();
	this->close();
}
